<template>
  <div class="schedule-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>日程列表</span>
          <el-button type="primary" @click="showScheduleModal">新增日程</el-button>
        </div>
      </template>

      <el-form :model="searchForm" layout="inline" class="search-form">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.diffTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keywords" placeholder="请输入关键词" />
        </el-form-item>
        <el-form-item label="工作类型">
          <el-select v-model="searchForm.laborType" style="width: 120px">
            <el-option value="" label="全部"></el-option>
            <el-option value="1" label="案头工作"></el-option>
            <el-option value="2" label="外勤工作"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSchedules">搜索</el-button>
          <el-button style="margin-left: 8px" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :columns="columns"
        :data="schedules"
        :pagination="pagination"
        @current-change="handleTableChange"
        row-key="id"
      >
        <template #default="{ column, row }">
          <template v-if="column.prop === 'labor_type'">
            <el-tag :type="getLaborTypeColor(row.labor_type)">
              {{ getLaborTypeText(row.labor_type) }}
            </el-tag>
          </template>
          <template v-else-if="column.prop === 'action'">
            <el-space>
              <el-button type="text" @click="editSchedule(row)">编辑</el-button>
              <el-button type="text" @click="deleteSchedule(row.id)">删除</el-button>
              <el-button type="text" @click="viewSchedule(row)">查看</el-button>
            </el-space>
          </template>
        </template>
      </el-table>
    </el-card>

    <!-- 日程编辑/新增模态框 -->
    <el-dialog
      v-model="scheduleModalVisible"
      :title="editingSchedule.id ? '编辑日程' : '新增日程'"
      @close="closeScheduleModal"
    >
      <el-form :model="scheduleForm" layout="vertical">
        <el-form-item label="标题" required>
          <el-input v-model="scheduleForm.title" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="scheduleForm.content" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="工作类型" required>
          <el-select v-model="scheduleForm.laborType">
            <el-option value="1" label="案头工作"></el-option>
            <el-option value="2" label="外勤工作"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" required>
          <el-date-picker
            v-model="scheduleForm.startTimeA"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            placeholder="请选择开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间" required>
          <el-date-picker
            v-model="scheduleForm.endTimeA"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            placeholder="请选择结束时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeScheduleModal">取消</el-button>
          <el-button type="primary" @click="saveSchedule">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { useOAStore } from '../../store/oa'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { Schedule } from '../../store/oa'
  import type { Dayjs } from 'dayjs'
  import dayjs from 'dayjs'

  const oaStore = useOAStore()

  // 搜索表单
  const searchForm = reactive({
    diffTime: [] as [Dayjs, Dayjs] | [],
    keywords: '' as string,
    laborType: '' as string,
  })

  // 表格列定义
  const columns = [
    {
      prop: 'title',
      label: '标题',
    },
    {
      prop: 'labor_type',
      label: '工作类型',
      width: 100,
    },
    {
      prop: 'labor_time',
      label: '工时',
    },
    {
      prop: 'start_time',
      label: '开始时间',
    },
    {
      prop: 'end_time',
      label: '结束时间',
    },
    {
      prop: 'create_time',
      label: '创建时间',
    },
    {
      prop: 'action',
      label: '操作',
      width: 180,
    },
  ]

  // 表格分页
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
  })

  // 日程数据
  const schedules = ref<Schedule[]>([])

  // 日程模态框
  const scheduleModalVisible = ref(false)

  // 编辑中的日程
  const editingSchedule = ref<any>({})

  // 日程表单
  const scheduleForm = reactive({
    id: 0,
    title: '' as string,
    content: '' as string,
    laborType: '1' as string,
    startTimeA: null as Dayjs | null,
    endTimeA: null as Dayjs | null,
  })

  // 获取工作类型文本
  const getLaborTypeText = (type: number) => {
    return type == 2 ? '外勤工作' : '案头工作'
  }

  // 获取工作类型颜色
  const getLaborTypeColor = (type: number) => {
    return type == 2 ? 'primary' : 'success'
  }

  // 搜索日程
  const searchSchedules = async () => {
    try {
      const params = {
        page: pagination.currentPage,
        limit: pagination.pageSize,
        diff_time:
          searchForm.diffTime.length > 0
            ? `${(searchForm.diffTime[0] as Dayjs).format('YYYY-MM-DD')}~${(searchForm.diffTime[1] as Dayjs).format('YYYY-MM-DD')}`
            : '',
        keywords: searchForm.keywords,
        labor_type: searchForm.laborType,
      }

      const res: any = await oaStore.getScheduleListAction(params)
      if (res?.data?.code === 0) {
        schedules.value = res.data.data || []
        pagination.total = res.data.count || 0
      } else {
        ElMessage.error(res?.data?.msg || '获取日程列表失败')
      }
    } catch (error) {
      ElMessage.error('获取日程列表失败')
    }
  }

  // 重置搜索
  const resetSearch = () => {
    searchForm.diffTime = []
    searchForm.keywords = ''
    searchForm.laborType = ''
    pagination.currentPage = 1
    searchSchedules()
  }

  // 处理表格分页变化
  const handleTableChange = (currentPage: number) => {
    pagination.currentPage = currentPage
    pagination.pageSize = pagination.pageSize
    searchSchedules()
  }

  // 显示日程模态框
  const showScheduleModal = () => {
    scheduleModalVisible.value = true
    editingSchedule.value = {}
    scheduleForm.id = 0
    scheduleForm.title = ''
    scheduleForm.content = ''
    scheduleForm.laborType = '1'
    scheduleForm.startTimeA = null
    scheduleForm.endTimeA = null
  }

  // 编辑日程
  const editSchedule = (record: any) => {
    scheduleModalVisible.value = true
    editingSchedule.value = record

    scheduleForm.id = record.id
    scheduleForm.title = record.title
    scheduleForm.content = record.content
    scheduleForm.laborType = String(record.labor_type)
    scheduleForm.startTimeA = record.start_time ? dayjs(record.start_time) : null
    scheduleForm.endTimeA = record.end_time ? dayjs(record.end_time) : null
  }

  // 查看日程
  const viewSchedule = (record: any) => {
    editSchedule(record)
  }

  // 保存日程
  const saveSchedule = async () => {
    try {
      const params = {
        id: scheduleForm.id,
        title: scheduleForm.title,
        content: scheduleForm.content,
        labor_type: scheduleForm.laborType,
        start_time_a: scheduleForm.startTimeA
          ? (scheduleForm.startTimeA as Dayjs).format('YYYY-MM-DD')
          : '',
        start_time_b: scheduleForm.startTimeA
          ? (scheduleForm.startTimeA as Dayjs).format('HH:mm')
          : '',
        end_time_a: scheduleForm.endTimeA
          ? (scheduleForm.endTimeA as Dayjs).format('YYYY-MM-DD')
          : '',
        end_time_b: scheduleForm.endTimeA ? (scheduleForm.endTimeA as Dayjs).format('HH:mm') : '',
        start_time: scheduleForm.startTimeA
          ? (scheduleForm.startTimeA as Dayjs).format('YYYY-MM-DD HH:mm')
          : '',
        end_time: scheduleForm.endTimeA
          ? (scheduleForm.endTimeA as Dayjs).format('YYYY-MM-DD HH:mm')
          : '',
      }

      const res: any = await oaStore.saveScheduleAction(params)
      if (res?.data?.code === 0) {
        ElMessage.success(res.data.msg || '保存成功')
        closeScheduleModal()
        searchSchedules()
      } else {
        ElMessage.error(res?.data?.msg || '保存失败')
      }
    } catch (error) {
      ElMessage.error('保存日程失败')
    }
  }

  // 关闭日程模态框
  const closeScheduleModal = () => {
    scheduleModalVisible.value = false
  }

  // 删除日程
  const deleteSchedule = (id: number) => {
    ElMessageBox.confirm('确定要删除这个日程吗？', '确认删除', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        const res: any = await oaStore.deleteScheduleAction(id)
        if (res?.data?.code === 0) {
          ElMessage.success(res.data.msg || '删除成功')
          searchSchedules()
        } else {
          ElMessage.error(res?.data?.msg || '删除失败')
        }
      })
      .catch(() => {
        // 用户取消删除
      })
  }

  // 组件挂载时获取数据
  onMounted(() => {
    searchSchedules()
  })
</script>

<style scoped>
  .schedule-container {
    padding: 16px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 16px;
  }
</style>
